package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.myBatisMapper.UserMapper;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Resource
    UserMapper userMapper;

    @PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest request){
        //1.先去查询数据库看username能否找到对应的user对象
        //找到就看密码是否匹配
        User user = userMapper.selectByName(username);
        if (user == null || !user.getPassword().equals(password)){
            //登陆失败
            System.out.println("登录失败!用户名或者密码错误! "+user);
            return new User();
        }
        //2.如果都匹配,登陆成功,创建会话
        HttpSession session = request.getSession(true);
        session.setAttribute("user",user);
        //在返回之前将密码制空,避免返回不必要的信息
        user.setPassword("");
        return user;
    }

    @PostMapping("/register")
    public Object register(String username,String password){
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            int ret = userMapper.insert(user);
            System.out.println("注册ret: " +ret);
            user.setPassword("");
        } catch (DuplicateKeyException e) {
            //用户名重复就会异常
            //注册失败
            user = new User();
            System.out.println("注册失败! username = " + username);
        }
        return user;
    }

    //获取客户端左上角用户名
    @GetMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest request){
        //1.先从请求中获取会话
        HttpSession session = request.getSession(false);
        if (session == null){
            //会话不存在
            System.out.println("用户尚未登录!");
            return new User();
        }
        //2.再从会话中获取到保存的用户对象
        User user = (User) session.getAttribute("user");
        if (user == null){
            System.out.println("当前获取不到user对象");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
